import os
import os.path
import sys
import shutil
import commands
import pwd
import gconf

# User's home directory
usrHome = os.path.expanduser("~")

# User's uid
uid = os.getuid()

# User's gid
gid = os.getgid()

# Path to custom fonts
customTTFDir = "/usr/share/fonts/truetype/custom"

# Path to Tahoma fonts
tahomaPath = os.path.join(usrHome , ".tmp/tahoma")

# Path to Tahoma hints
customHints = "/etc/defoma/hints/custom.hints"

# Path to Defoma program
defomaPath = "/usr/bin/defoma-font"

# Path to .fonts.conf
fontConfPath = os.path.join(usrHome , ".fonts.conf")

# User fonts path
userFontPath = os.path.join(usrHome , ".fonts")

# Path to .gtkrc.mine
gtkrcConfPath = os.path.join(usrHome , ".gtkrc.mine")

# Path to samplefile
samplePath = os.path.join(usrHome , ".samplefile")

# Hints Data
hintsData = """category truetype
begin /usr/share/fonts/truetype/custom/tahoma.ttf
  Family = Tahoma
  FontName = Tahoma-Regular
  Encoding = Unicode
  Location = Magyar Dutch Spanish Czech Russian English Catalan Slovak Italian Turkish Danish Slovenian Basque Portuguese German Polish Swedish Norwegian French Finnish Greek
  Charset = ISO8859-1 ISO8859-2 ISO8859-3 ISO8859-4 ISO8859-5 ISO8859-7 ISO8859-9 ISO8859-10 ISO8859-13 ISO8859-14 ISO8859-15 KOI8-R KOI8-U CP1251 VISCII1.1-1 TCVN-5712 ISO10646-1
  UniCharset = ISO8859-1 ISO8859-2 ISO8859-3 ISO8859-4 ISO8859-5 ISO8859-7 ISO8859-9 ISO8859-10 ISO8859-13 ISO8859-14 ISO8859-15 KOI8-R KOI8-U CP1251 VISCII1.1-1 TCVN-5712
  GeneralFamily = SansSerif
  Weight = Medium
  Width = Variable
  Shape = NoSerif Upright
  Foundry = Microsoft
  Priority = 20
end
begin /usr/share/fonts/truetype/custom/tahomabd.ttf
  Family = Tahoma
  FontName = Tahoma-Bold
  Encoding = Unicode
  Location = Magyar Dutch Spanish Czech Russian English Catalan Slovak Italian Turkish Danish Slovenian Basque Portuguese German Polish Swedish Norwegian French Finnish Greek
  Charset = ISO8859-1 ISO8859-2 ISO8859-3 ISO8859-4 ISO8859-5 ISO8859-7 ISO8859-9 ISO8859-10 ISO8859-13 ISO8859-14 ISO8859-15 KOI8-R KOI8-U CP1251 VISCII1.1-1 TCVN-5712 ISO10646-1
  UniCharset = ISO8859-1 ISO8859-2 ISO8859-3 ISO8859-4 ISO8859-5 ISO8859-7 ISO8859-9 ISO8859-10 ISO8859-13 ISO8859-14 ISO8859-15 KOI8-R KOI8-U CP1251 VISCII1.1-1 TCVN-5712
  GeneralFamily = SansSerif
  Weight = Bold
  Width = Variable
  Shape = NoSerif Upright
  Foundry = Microsoft
  Priority = 20
end
"""

# Fonts.conf Data
fontData = """<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<!-- UNCOMMENT THIS SECTION TO ENABLE ANTIALIAS FOR BOLD FONTS --> <match target="font" >
  <test name="weight" >
   <const>bold</const>
   <const>black</const>
  </test>
  <test compare="more" name="pixelsize" qual="any" >
   <double>12</double>
  </test>
  <edit mode="assign" name="antialias" >
   <bool>true</bool>
  </edit>
 </match>
 <match target="pattern" >
  <test name="family" qual="any" >
   <string>Bitstream Vera Sans</string>
  </test>
  <edit mode="assign" name="family" >
   <string>Arial</string>
  </edit>
 </match>
 <match target="pattern" >
  <test name="family" qual="any" >
   <string>Helvetica</string>
  </test>
  <edit mode="assign" name="family" >
   <string>Arial</string>
  </edit>
 </match>
 <match target="pattern" >
  <test name="family" qual="any" >
   <string>Palatino</string>
  </test>
  <edit mode="assign" name="family" >
   <string>Georgia</string>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="rgba" >
   <const>rgb</const>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="hinting" >
   <bool>true</bool>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="hintstyle" >
   <const>hintfull</const>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="antialias" >
   <bool>true</bool>
  </edit>
 </match>
 <match target="font" >
  <test compare="more_eq" name="size" qual="any" >
   <double>0</double>
  </test>
  <test compare="less_eq" name="size" qual="any" >
   <double>11</double>
  </test>
  <edit mode="assign" name="antialias" >
   <bool>false</bool>
  </edit>
 </match>
 <match target="font" >
  <test compare="more_eq" name="pixelsize" qual="any" >
   <double>0</double>
  </test>
  <test compare="less_eq" name="pixelsize" qual="any" >
   <double>15</double>
  </test>
  <edit mode="assign" name="antialias" >
   <bool>false</bool>
  </edit>
 </match>
</fontconfig>
"""

# .gtkrc.mine Data
gtkData = """style "user-font"
{
  fontset="-microsoft-tahoma-medium-r-normal-*-10-*-*-*-p-*-*"
}
widget_class "*" style "user-font"
"""

#### Validate dependency satisfaction ####
#===============================================================================
#sys.stdout.write("Checking dependencies...")
#if not os.path.exists(defomaPath):
#    sys.stdout.write("   Failed!\n")
#    print "Dependency not satisfied: Defoma\n"
#    sys.exit()
#    
#sys.stdout.write("   Done!\n")
#===============================================================================

#### Validate paths ####

#===============================================================================
## Create the custom fonts folder if it doesn't already exist
#sys.stdout.write((r"Checking custom fonts path: " + customTTFDir + " ..."))
#if not os.path.exists(customTTFDir):
#    os.mkdir(customTTFDir)
#
#sys.stdout.write("   Done!\n")
#
## Copy Tahoma font files
#sys.stdout.write("Copy Tahoma font files from: " + tahomaPath + "   to:   " + customTTFDir + " ...")
#shutil.copy(os.path.join(tahomaPath, "tahoma.ttf"), customTTFDir)
#shutil.copy(os.path.join(tahomaPath, "tahomabd.ttf"), customTTFDir)
#sys.stdout.write("   Done!\n")
#===============================================================================

#===============================================================================
## Create Tahoma hints file if it doesn't exist
#sys.stdout.write("Setting up the hints file for Tahoma: " + customHints + " ...")
#if not os.path.exists(customHints):
#    os.mknod(customHints)
#
#handle = open(customHints,"r+a")
#if handle.read().find(hintsData) < 0:
#    handle.write(hintsData+"\n")
#handle.close()
#
#sys.stdout.write("   Done!\n")
#===============================================================================
    
# Register the Tahoma font
sys.stdout.write("Reconfiguring Defoma...")
proc = commands.getstatusoutput("gksu -D \"Please enter your credentials for running:\n defoma-font -v register-all\" " + defomaPath + " -v register-all " + customHints)
procErr = proc[0]
procOut = proc[1]

if procErr > 0:
    sys.stdout.write("   Failed!\n\n")
    print "There was an error reconfiguring defoma:\n"
    print procOut
    sys.exit()
    
sys.stdout.write("  Done!\n")

# Configure system-wide fontconfig rendering method
sys.stdout.write("Reconfiguring fontconfig")
sys.stdout.write(".")
sys.stdout.write(".")
sys.stdout.write(".")

proc = commands.getstatusoutput("gksu -D \"Please enter your credentials for running:\n dpkg-reconfigure fontconfig\" dpkg-reconfigure fontconfig")
procErr = proc[0]
procOut = proc[1]

if procErr > 0:
    sys.stdout.write("   Failed!\n\n")
    print "There was an error reconfiguring fontconfig:\n"
    print procOut
    sys.exit()

sys.stdout.write("   Done!\n")

# Turn autohinting on for fonts larger than 12 pts (this will include the Firefox fonts) and perform font substitution for websites using Bitstream, Helvetica and Palatino fonts.
sys.stdout.write("Setting up " + fontConfPath + " for logical autohinting...")
if not os.path.exists(fontConfPath):
    os.mknod(fontConfPath)

handle = open(fontConfPath,"r+a")
if handle.read().find(fontData) < 0:
    handle.write(fontData+"\n")
handle.close()

sys.stdout.write("   Done!\n")

# Configure GTK1 applications to use Tahoma
sys.stdout.write("Setting up " + gtkrcConfPath + " to enable Tahoma in GTK1 applications...")
if not os.path.exists(gtkrcConfPath):
    os.mknod(gtkrcConfPath)

handle = open(gtkrcConfPath,"r+a")
if handle.read().find(gtkData) < 0:
    handle.write(gtkData+"\n")
handle.close()

sys.stdout.write("   Done!\n")

#===============================================================================
## Setting file permissions
#sys.stdout.write("Setting file permissions...")
#
#os.chown(fontConfPath, uid, gid)
#os.chown(gtkrcConfPath, uid, gid)
#
#sys.stdout.write("   Done!\n")
#===============================================================================

# Setup Gnome font preferences
sys.stdout.write("Setting up Gnome font preferences...")

client = gconf.client_get_default()
client.set_value('/desktop/gnome/interface/document_font_name',"Tahoma 8")
client.set_value('/desktop/gnome/interface/font_name',"Tahoma 8")
client.set_value('/desktop/gnome/interface/monospace_font_name',"Courier New 9")
client.set_value('/apps/metacity/general/titlebar_font',"Tahoma Bold 9")
client.set_value('/apps/nautilus/preferences/desktop_font',"Tahoma 8")

sys.stdout.write("   Done!\n")

# Rehup gnome-panel and nautilus
sys.stdout.write("Restarting gnome-panel and nautilus...")

commands.getstatusoutput("killall gnome-panel")
commands.getstatusoutput("killall nautilus")

sys.stdout.write("   Done!\n")

print "Gnome Panel and Nautilus have been restarted for you."
print "You will need to log out and log back in to see the full effect."